<template>
  <el-dialog
    :title="form.classId ? '编辑商品' : '新增商品'"
    :visible.sync="visible"
    width="35%"
    :close-on-click-modal="false"
  >
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="商品名称：" prop="skuName">
        <el-input v-model="form.skuName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="品牌：" prop="brandName">
        <el-input v-model="form.brandName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="商品价格(元)：" prop="price">
        <el-input-number
          :step="0.5"
          v-model="form.price"
          controls-position="right"
          placeholder="请输入"
          :min="0.01"
          :max="1000"
          :precision="2"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="商品类型：" prop="classId">
        <el-select v-model="form.classId" placeholder="请选择">
          <el-option
            v-for="item in pullList"
            :key="item.classId"
            :label="item.className"
            :value="item.classId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="规格：" prop="unit">
        <el-input v-model="form.unit" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="商品图片：">
        <template #default>
          <el-upload
            class="uppic"
            action="#"
            list-type="picture-card"
            :file-list="fileList"
            :limit="limit"
            :class="fileList.length === limit ? 'hideAdd' : ''"
            :before-upload="beforeUpload"
            :http-request="httpRequest"
            :on-change="handleChange"
            :on-remove="removePic"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <span class="yaoqiu">支持扩展名：jpg、png，文件不得大于100kb</span>
        </template>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="cancel" class="cancel"
          >取消</el-button
        >
        <el-button class="sure" @click="sure">确认</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import COS from 'cos-js-sdk-v5'
import { getClassList, uploadPic, editGoodsInfo } from '@/api/gdInfo'
const cos = new COS({
  SecretId: 'AKID63mIciZCbmkVMzNXTDm9JFyShjXCh086',
  SecretKey: 'ylNn8II5f2FKFxgNtGSRCnPvEKCtOfjc'
})
export default {
  name: 'Dkd3SkuDialog',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      visible: false,
      form: {},
      pullList: [],
      fileList: [],
      rules: {
        skuName: [{ required: true, message: '请输入', trigger: 'blur' }],
        brandName: [{ required: true, message: '请输入', trigger: 'blur' }],
        classId: [{ required: true, message: '请输入', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      flag: 0
    }
  },

  mounted () {},
  watch: {
    visible (val) {
      if (!val) {
        this.$refs.form.resetFields()
        this.form = {}
        this.fileList = []
        this.pullList = []
      } else {
        this.form.skuImage &&
          (this.fileList = [
            {
              url: this.form.skuImage
            }
          ])
      }
    }
  },
  methods: {
    cancel () {
      // this.form = {}
      this.visible = false
    },
    async getPullList () {
      const res = await getClassList({ pageIndex: 1, pageSize: 100000 })
      this.pullList = res.currentPageRecords
    },
    handleChange (file, fileList) {
      this.fileList = fileList
    },
    beforeUpload (file) {
      // 要开始做文件上传的检查了
      // 文件类型 文件大小
      // console.log(file)
      const types = ['image/jpeg', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!')
        return false
      }
      //  检查大小
      const maxSize = 1000 * 1024
      if (maxSize < file.size) {
        this.$message.error('图片大小最大不能超过100KB')
        return false
      }
      return true
    },
    removePic (file, fileList) {
      this.fileList = fileList
    },
    httpRequest (data) {
      // console.log(data)
      cos.uploadFile(
        {
          Bucket: 'giao-1317377860' /* 填写自己的 bucket，必须字段 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: data.file
            .name /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
          Body: data.file, // 上传文件对象
          onProgress: function (progressData) {
            // console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          if (err || data.statusCode !== 200) {
            this.$message.error('亲,上传失败,请重试')
          } else {
            this.form.skuImage = 'https://' + data.Location
            this.$message.success('亲,上传成功啦亲')
          }
        }
      )
    },
    async sure () {
      // editGoodsInfo
      await this.$refs.form.validate()
      if (this.flag === 1) {
        // 编辑
        const standard = [
          'brandName',
          'classId',
          'price',
          'skuImage',
          'skuName',
          'unit'
        ]
        const editForm = {}
        Object.keys(this.form).forEach((key) => {
          if (standard.includes(key)) {
            editForm[key] = this.form[key]
          }
        })
        console.log(editForm)
        await editGoodsInfo(editForm)
      } else {
        // 新增
        await uploadPic(this.form)
      }
      this.visible = false
      this.$emit('flash')
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-dialog {
  border-radius: 20px;
}
.el-input-number {
  width: 100%;
}
/deep/.el-form-item__label {
  width: 120px !important;
}
/deep/.el-form-item__content {
  margin-left: 120px !important;
}
/deep/.el-form-item {
  &:last-of-type {
    .el-form-item__content {
      margin-left: 0 !important;
    }
  }
}
.el-select {
  width: 100% !important;
}
.cancel {
  color: #333;
  border: none;
  background-color: #fbf4f0 !important;
  &:hover {
    background-color: #f3e7e1 !important;
  }
}
.sure {
  color: #fff;
  border: none;
  background: linear-gradient(135deg, #ff8739, #ff702b) !important;
  &:hover {
    background: linear-gradient(135deg, #fc773d, #e54b15) !important;
  }
}
/deep/.hideAdd .el-upload--picture-card {
  display: none !important;
}
/deep/.el-upload-list {
  width: 80px;
  height: 80px;
  text-align: center;
  line-height: 80px;
  .el-progress--circle {
    width: 80px !important;
    height: 80px !important;
  }
  .el-upload-list__item {
    height: 80px !important;
    width: 80px !important;
  }
}
.uppic {
  height: 80px !important;
  text-align: left;
  /deep/.el-upload {
    height: 80px !important;
    width: 80px !important;
    line-height: 80px;
  }
}
.yaoqiu {
  float: left;
}
</style>
